package ar.com.blacktobacco;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class RSSParserHandler extends DefaultHandler {

	private RSSChannel channel;
	private RSSItem item;
	private StringBuilder builder;

	public RSSChannel getChannel() {
		return channel;
	}

	public void setChannel(RSSChannel channel) {
		this.channel = channel;
	}

	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
		builder = new StringBuilder();
	}

	@Override
	public void endDocument() throws SAXException {
		super.startDocument();
		builder = null;
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		super.characters(ch, start, length);
		builder.append(ch, start, length);
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);
		if (localName.equalsIgnoreCase("channel")) {
			channel = new RSSChannel();
			channel.setItem(new ArrayList<RSSItem>());
		} else if (localName.equalsIgnoreCase("item")) {
			item = new RSSItem();
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		super.endElement(uri, localName, qName);
		if (item != null && localName.equalsIgnoreCase("title")) {
			item.setTitle(builder.toString());
		} else if (localName.equalsIgnoreCase("item")) {
			channel.getItem().add(item);
			item = null;
		} else if (channel != null && localName.equalsIgnoreCase("title")) {
			channel.setTitle(builder.toString());
		}
		builder.setLength(0);
	}

}
